package com.dyzx.hbb.security.controller;

import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.modules.sys.entity.SysUser;
import com.dyzx.hbb.modules.sys.service.SysUserService;
import com.dyzx.hbb.modules.sys.vo.UserPasswordForgotChangeVO;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import com.dyzx.hbb.security.model.LoginDTO;
import com.dyzx.hbb.security.model.SysUserInfo;
import com.dyzx.hbb.security.service.AuthService;
import com.dyzx.hbb.aliyun.sms.utils.Utils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * 认证授权控制器
 * 负责处理用户登录、退出、密码找回等认证相关操作
 */
@Tag(name = "01.认证授权", description = "认证授权相关接口，包括登录、退出、密码找回等")
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthService authService;

    @Autowired
    private SysUserService userService;

        /**
     * 账号密码登录
     * @param loginDTO 登录信息，包含账号和密码
     * @return 登录结果，包含用户信息和Token
     */
    @Operation(summary = "账号密码登录", description = "使用账号和密码进行系统登录")
    @PostMapping("/login")
  //  @Operation(summary = "用户登录", description = "通过用户名和密码进行用户登录")
    public Result<SysUserInfo> login(
            @Parameter(description = "登录信息对象") @RequestBody LoginDTO loginDTO) {
        System.out.println("login");
        System.out.println(loginDTO);
        System.out.println(loginDTO.getAccount());
        System.out.println(loginDTO.getPassword());
        return authService.login(loginDTO.getAccount(), loginDTO.getPassword());
    }



    /**
     * 退出登录
     * @return 退出结果
     */
    @Operation(summary = "退出登录", description = "退出当前登录状态")
    @PostMapping("/logout")
  //  @Operation(summary = "用户登出", description = "用户退出登录")
    public Result<Void> logout() {
        return authService.logout();
    }



    //登陆模块中实现 force_out
    /**
     * 强制退出登录
     * @param userId 用户ID
     * @return 操作结果
     */
    @Operation(summary = "强制退出登录", description = "强制指定用户退出登录状态")
    @PostMapping("/force_out")
  //  @Operation(summary = "强制登出", description = "强制指定用户退出登录")
    public Result<Void> forceOut(
            @Parameter(description = "用户ID") @RequestParam Long userId) {
    boolean flag=authService.forceOut(userId);
        return flag?Result.ok():Result.error();
    }

    /**
     * 找回密码
     * @param vo 密码找回信息，包含手机号和验证码
     * @return 操作结果
     */
    @Operation(summary = "找回密码", description = "通过手机验证码找回密码")
    @PutMapping("/forgot_pass")
    public Result<Boolean> forgotPass(
            @Parameter(description = "密码找回信息对象") @RequestBody UserPasswordForgotChangeVO vo) {
        if (StringUtils.isBlank(vo.getPhone())) {
            return Result.error("手机号不能为空");
        }
        if (!vo.getPhone().matches("^1[3-9]\\d{9}$")) {
            return Result.error("手机号格式不正确");
        }
        // 验证短信验证码
        if (!userService.validateSmsCode(vo.getPhone(), vo.getVcode())) {
            return Result.error("短信验证码错误");
        }
      //  String code = RandomUtil.randomString("0123456789Qqwertyuiopasdfghjklzxcvbnm", 6);
        int code = Utils.randomCode();
        // 生成随机密码
        String newPassword = String.valueOf(code);



        // 更新密码
        SysUser user = userService.getByPhone(vo.getPhone());
        if (user == null) {
            return Result.error("用户不存在");
        }

        user.setPassword(passwordEncoder.encode(newPassword));
        user.setUpdateDate(System.currentTimeMillis());
        boolean data = userService.updateById(user);
        if(data){
            // 发送新密码到手机/邮箱
            userService.sendNewPassword(vo.getPhone(), newPassword);
        }
        return Result.ok(data);
    }


    // get  /auth/getLoginUserInfo
    @Operation(summary = "获取当前登录用户信息")
    @GetMapping
    public Result<SysUserInfo> getLoginUserInfo() {

        SysUserInfo loginUserInfo = userService.getLoginUserInfo(SecurityContextHolder.getUserId());
        return Result.ok(loginUserInfo);
    }
    }